package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
	"log"
	"net/http"
	"strings"
)

type GetConfigParamType struct {
	Token string `json:"token"`
	InstanceName string `json:"instanceName"`
}

func GetConfig(c *gin.Context) {
	/**
	@params:
		token: the token to get config, actually is a jwt, contains userID
		instanceName: the config instance name
	*/

	var getConfigParam GetConfigParamType
	var errMsg string
	if err := c.BindJSON(&getConfigParam); err != nil {
		log.Println(err)
		return
	}
	if nameLength := len(getConfigParam.InstanceName); nameLength < 1 || nameLength > 50 {
		errMsg = "length of instance name should between 1 and 50"
		log.Println(errMsg)
		c.String(http.StatusBadRequest, errMsg)
		return
	}

	// check token
	if _, err := util.ParseToken(getConfigParam.Token); err != nil {
		log.Println("获取kconfig时， token验证错误： " + err.Error())
		c.String(http.StatusUnauthorized, "token错误")
		return
	}

	temContent, err := models.GetConfTemplateContent("testing")
	if err != nil || temContent == ""{
		log.Println("获取karbon config template内容时错误")
		c.String(http.StatusBadRequest, "获取template内容错误")
		return
	}

	confItemsReplace, err := models.GetConfItemsByInstanceName(getConfigParam.InstanceName)
	if err != nil {
		errMsg = fmt.Sprintf("get config items of instance: %s error: %s", getConfigParam.InstanceName, err.Error())
		log.Println(errMsg)
		c.String(http.StatusBadRequest, errMsg)
		return
	}

	// check config
	content, errMsgList, err := util.CheckAndReplace(temContent, confItemsReplace)
	if err != nil {
		log.Println(err)
		if errMsgList != nil {
			errMsg = strings.Join(errMsgList, ",")
			log.Println(errMsg)
			c.String(http.StatusBadRequest, errMsg)
			return
		} else {
			c.String(http.StatusBadRequest, err.Error())
		}
	}

	c.String(http.StatusOK, content)
}
